package com.hjx.movie.core.security.auth;



import com.hjx.movie.core.security.model.AuthUser;
import com.hjx.movie.core.security.service.IAuthService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>Title:加载用户权限</p>
 * <p>Description:</p>
 *
 * @author hjx
 * @date 2020/6/10 - 9:07
 */
@Service
public class AuthUserDetailsService implements UserDetailsService {
    @Resource
    IAuthService authService;
    @Override
    public UserDetails loadUserByUsername(String uid) throws UsernameNotFoundException {
        //根据用户编号查询用户信息
        AuthUser user = authService.findUserById(uid);
        //根据用户编号查询用户的角色
        List<String> roleCodes = authService.findRoleByUserId(user.getUserId());
        //根据用户的角色ID查询角色所拥有的权限
//        List<String> auth = authService.findAuthByRoleCode(roleCodes);
        List<Long> roleIds = authService.findRoleIdByUserId(Long.parseLong(uid));
        List<String> auth = authService.findAuthByRoleId(roleIds);
        //将角色添加到权限的集合中
        auth.addAll(roleCodes);
        List<GrantedAuthority> grantedAuthorities =
                AuthorityUtils.createAuthorityList(auth.toArray(new String[0]));
        //返回一个User对象
        //使用uid作为 权限USER的username
        return new User(user.getUserId().toString(),user.getPassword(),grantedAuthorities);
    }
}
